package cn.coldleaf.wiki.configure;

import cn.coldleaf.wiki.interceptors.AbstractInterceptor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.context.annotation.ClassPathScanningCandidateComponentProvider;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.type.filter.AssignableTypeFilter;
import org.springframework.web.servlet.config.annotation.InterceptorRegistration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import java.util.Set;

/**
 * @datetime 2023/10/15 下午3:25
 * @user cold
 **/
@Slf4j
@Configuration
public class WebConfig implements WebMvcConfigurer {
    @Autowired
    private AppConfig appConfig;
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        log.info("加载拦截器");
        ClassPathScanningCandidateComponentProvider provider = new ClassPathScanningCandidateComponentProvider(false);
        provider.addIncludeFilter(new AssignableTypeFilter(AbstractInterceptor.class));
        Set<BeanDefinition> candidates = provider.findCandidateComponents("cn.coldleaf.wiki.interceptors");
        log.info("获取{}个拦截器",candidates.size());
        try {
            for (BeanDefinition candidate : candidates) {
                Class<?> clazz = Class.forName(candidate.getBeanClassName());
                AbstractInterceptor interceptor = (AbstractInterceptor) clazz.newInstance();
                interceptor.setAppConfig(appConfig);
                log.info("加载[{}]拦截器",interceptor.getName());
                InterceptorRegistration registration = registry.addInterceptor(interceptor);
                if (interceptor.getPatterns() != null && interceptor.getPatterns().length > 0) {
                    registration.addPathPatterns(interceptor.getPatterns());
                }
                if (interceptor.getExcludePathPatterns() != null
                        && interceptor.getExcludePathPatterns().length > 0){
                    registration.excludePathPatterns(interceptor.getExcludePathPatterns());
                }
            }
        }catch (Throwable e){
            log.error("加载拦截器失败",e);
        }
    }

}
